package net.sourceforge.peertwitter.mbpast;

import java.util.concurrent.atomic.AtomicInteger;

import net.sourceforge.peertwitter.mbpast.messaging.ReplicaTimestampRequest;

import rice.environment.logging.Logger;
import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.NodeHandleSet;

public class TimestampRequester implements Runnable {

	private final Endpoint endpoint;
	private final Id idToGetReplica;
	private static AtomicInteger uniqueId = new AtomicInteger(0);
	
	private NodeHandleSet replicas;
	private final int myUniqueId;
	private Logger logger;
	
	public TimestampRequester(Endpoint endpoint, Id idToGetReplica, NodeHandleSet replicas) {
		this.endpoint = endpoint;
		this.idToGetReplica = idToGetReplica;
		this.myUniqueId = uniqueId.getAndIncrement();
		this.replicas = replicas;
		this.logger = endpoint.getEnvironment().getLogManager().getLogger(TimestampRequester.class, endpoint.getId().toString());
	}


	@Override
	public void run() {
		ReplicaTimestampRequest request = new ReplicaTimestampRequest(this.endpoint.getLocalNodeHandle(), idToGetReplica);
		for (int current = 0; current < replicas.size(); current++) {
			this.logger.log("Requesting replica timestamp from " + replicas.getHandle(current).getId());
			this.endpoint.route(replicas.getHandle(current).getId(), request, replicas.getHandle(current));
		}
	}

	public int getUniqueId() {
		return myUniqueId;
	}

}
